package org.jpro.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.jpro.common.http.ResponseVO;
import org.jpro.common.util.JsonMapper;
import org.jpro.exception.BaseException;
import org.jpro.exception.ExceptionCode;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import lombok.extern.slf4j.Slf4j;

/**
 * <P>功能描述 : Spring MVC 全局异常， 统一异常格式</P>
 * <P>File name : GlobalExceptionHandler </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/1/1 上午1:53</P>
 */
@Slf4j
@ControllerAdvice(annotations = { Controller.class, RestController.class })
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * 捕获所有Controller中@RequestMapping注解的方法执行过程中抛出的BaseException
     */
    @ResponseStatus(value = HttpStatus.OK)
    @ExceptionHandler(value = { Exception.class })
    public void handleException(Exception ex, HttpServletResponse response) throws IOException {
        ResponseVO responseVO;
        if (ex instanceof BaseException) {
            BaseException baseException = (BaseException) ex;
            responseVO = new ResponseVO(baseException.getCode());
        } else {
            log.error("捕获到未知异常", ex);
            responseVO = new ResponseVO(ExceptionCode.FAILED, ex.getMessage());
        }
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JsonMapper.toJson(responseVO));
        writer.close();
    }
}
